package com.ruoyi.yl.controller;

import com.alibaba.fastjson2.JSONObject;
import com.alibaba.nacos.api.common.Constants;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.common.domain.body.WeChatLoginBody;
import com.ruoyi.common.domain.body.WeChatUserBody;
import com.ruoyi.yl.process.WeChatLoginProcess;
import com.ruoyi.yl.utils.LoginUserUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;

/**
 * 登录验证
 *
 * @author ruoyi
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class LoginController {


    @Resource
    private WeChatLoginProcess weChatLoginProcess;


    @PostMapping("/wxLogin")
    public AjaxResult login(@RequestBody WeChatLoginBody loginBody) {
        // 生成令牌
        WeChatLoginProcess.WxSessionResult login = weChatLoginProcess.login(loginBody);

        return AjaxResult.success(new HashMap<String, Object>() {{
            put(Constants.TOKEN, login.token());
            put("wxSessionKey", login.wxSessionKey());
            put("openId", login.openId());
//
        }});
    }




    @PostMapping("/get/userInfo")
    public AjaxResult getUserInfo() {
        //刷新后重新获取不然没办法保证及时同步
        LoginUserUtil.refreshUsers();
        log.info("刷新用户信息:{}", SecurityUtils.getLoginUser().getUsers());
        return AjaxResult.success(SecurityUtils.getLoginUser().getUsers());
    }

    @PostMapping("/update/userInfo")
    public AjaxResult initUserInfo(@RequestBody WeChatUserBody body) {
        weChatLoginProcess.updateUserInfo(body.getNickName(),body.getPhoneNumber(),body.getAvatarUrl());
        return AjaxResult.success();
    }


    @PostMapping("/get/phone")
    public AjaxResult initUserPhone(@RequestBody WeChatLoginBody body) {

        String decrypt = weChatLoginProcess.decrypt(body.getPhoneEncryptedData(), body.getWxSessionKey(), body.getPhoneIv());
        return AjaxResult.success(new HashMap<String, Object>() {{
            put("phone", JSONObject.parseObject(decrypt).get("phoneNumber"));
        }});
    }




}
